package com.dd.controller;

import com.dd.entity.User;
import com.dd.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * ProjectName: springMvc01->UserController
 * Description: TODO：
 * Author: 丘丘
 * DateTime: 2024/12/27 14:18
 */
@Controller
@ResponseBody  // 把注解写在类上，可以让类中的方法继承
@RequestMapping(produces = "application/json;charset=utf-8")
public class UserController {
    // controller 依赖 service
    @Autowired
    private UserService userService;

    @RequestMapping("/selectAllUsers")
    @ResponseBody
    public List<User> selectAllUsers() {
        return userService.selectAllUsers();
    }


    // 根据编号查用户 ， 网页要修改用户，先查这个用户，再回显到表单，
    @RequestMapping("/selectUserById")  // 查询和删除，这都是用url里通过?来通过get方式拼接参数  http://localhost/selectUserById?id=10
    User selectUserById(int id) {
        User user = userService.selectUserById(id);
        return user!=null?user:new User(10000,"查此无人");
    }

    // 根据编号删除用户， http://localhost/selectUserById?id=10 可以直接通过浏览器地址发送
    @RequestMapping(value = "/deleteUserById")
    String deleteUserById(int id){
     return userService.deleteUserById(id)>0?"成功":"失败";
    }

    // 添加新用户,要让浏览器发送一个json对象，加RequestBody
    @RequestMapping("insertUser")
    String insertUser(@RequestBody User user){
        return userService.insertUser(user)>0?"成功":"失败";
    }

    // 修改旧用户
    @RequestMapping("updateUser")
    String updateUser(@RequestBody User user){
        return userService.updateUser(user)>0?"成功":"失败";
    }

    // 根据用户名查询用户，用来模糊查询,返回值 http://localhost/selectUserById?username=王维
    @RequestMapping("selectUserByName")
    List<User> selectUserByName(String username){
        return userService.selectUserByName(username);
    }

}
